<template>
  <a-card :bordered='false'>

    <!-- 查询区域 -->
    <div class='table-page-search-wrapper'>
      <a-form layout='inline'>
        <a-row :gutter='12'>
          <a-col :md='4' :sm='8'>
            <a-form-item label='所属项目'>
              <a-select show-search :filter-option='filterOption' v-model='queryParam.projectId' placeholder='请输入所属项目'
                        style='margin-right: 20px'>
                <a-select-option value=''>请选择项目</a-select-option>
                <a-select-option v-for='item in projectList' :label='item.name' :value='item.id' :key='item.id'>
                  <span style='float: left'>{{ item.name }}</span>
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='4' :sm='8'>
            <a-form-item label='设备sn'>
              <a-input placeholder='请输入sn查询' v-model='queryParam.deviceSn'></a-input>
            </a-form-item>
          </a-col>

          <a-col :md='4' :sm='8'>
            <a-form-item label='设备类型'>
              <a-select
                @click.native='searchTypeList'
                v-model='queryParam.deviceCode'
                placeholder='全部'>
                <a-select-option v-for='(deviceType,index) in this.deviceTypeList' :key='index'
                                 :value='deviceType.name'>
                  {{ deviceType.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='4' :sm='8'>
            <a-form-item label='设备别名'>
              <a-input placeholder='请输入设备别名查询' v-model='queryParam.deviceAlias'></a-input>
            </a-form-item>
          </a-col>

          <a-col :md='4' :sm='8'>
            <span style='float: left;overflow: hidden;' class='table-page-search-submitButtons'>
              <a-button type='primary' @click='searchQuery' icon='search'>查询</a-button>
              <a-button type='primary' @click='searchReset' icon='reload' style='margin-left: 8px'>重置</a-button>
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class='table-operator'>
      <a-button @click='handleAdd' type='primary' icon='plus' style='margin-right:10px'>新增</a-button>
      <a-dropdown v-if='selectedRowKeys.length > 0'>
        <a-menu slot='overlay'>
          <a-menu-item key='1' @click='batchDel'>
            <a-icon type='delete' />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style='margin-left: 8px'> 批量操作
          <a-icon type='down' />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class='ant-alert ant-alert-info' style='margin-bottom: 16px;'>
        <i class='anticon anticon-info-circle ant-alert-icon'></i> 已选择 <a
        style='font-weight: 600'>{{ selectedRowKeys.length }}</a>项
        <a style='margin-left: 24px' @click='onClearSelected'>清空</a>
      </div>

      <a-table
        ref='table'
        size='middle'
        bordered
        rowKey='id'
        :columns='columns'
        :dataSource='dataSource'
        :pagination='ipagination'
        :loading='loading'
        :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}'
        @change='handleTableChange'>

        <span slot='action' slot-scope='text, record'>
          <a @click='handleEdit(record)'>编辑</a>

          <a-divider type='vertical' />
          <a-dropdown>
            <a class='ant-dropdown-link'>更多 <a-icon type='down' /></a>
            <a-menu slot='overlay'>
              <a-menu-item>
                <a-popconfirm title='确定删除吗?' @confirm='() => handleDelete(record.id)'>

                    删除
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item>
                 <a @click='openDoors(record)'>开门</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>

      <!--新增区域-->
      <add-device-modal ref='addDeviceModal' @ok='modalFormOk'></add-device-modal>
    </div>
    <!-- table区域-end -->

  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { deleteAction, getAction, downFile } from '@/api/manage'
import { filterObj } from '@/utils/util'
import AddDeviceModal from '@views/passage/device/modules/AddDeviceModal'
import { getProjectList } from '@api/api'

export default {
  name: 'DeviceList',
  mixins: [JeecgListMixin],
  components: {
    AddDeviceModal
  },
  data() {
    return {
      description: '门禁设备管理页面',
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '项目名称',
          align: 'center',
          dataIndex: 'projectName'
        },

        {
          title: '设备类型',
          align: 'center',
          dataIndex: 'deviceCode'
        },
        {
          title: '设备型号',
          align: 'center',
          dataIndex: 'deviceModel_dictText'
        },
        {
          title: '设备别名',
          align: 'center',
          dataIndex: 'deviceAlias'
        },
        {
          title: '设备sn号',
          align: 'center',
          dataIndex: 'deviceSn'
        },

        {
          title: '通讯地址',
          align: 'center',
          dataIndex: 'swapAddress'
        },
        {
          title: '通讯方式',
          align: 'center',
          dataIndex: 'swapType'
        },
        {
          title: '更新时间',
          align: 'center',
          dataIndex: 'updateTime'
        },
        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createUser'
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/device/list',
        typeList: '/devicetype/deviceType/list',
        delete: '/device/delete',
        deleteBatch: '/device/deleteBatch',
        openDoor: '/device/openDoor',
        exportXlsUrl: '/device/exportXls',
        importExcelUrl: 'device/device/importExcel'
      },
      queryParam: {
        'type': '-1',
        'deviceNum': '',
        'projectRegionName': '',
        'deviceCode': ''
      },
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      //下拉框
      deviceTypeList: [],
      projectList: []

    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },


  //每次页面加载前
  created() {
    console.log(this.$route.query)
    this.initProjectList()
    this.queryParam.deviceType = this.$route.query.name

  },
  methods: {
    filterOption(input, option) {
      let com = option.componentOptions
      let name = String(com.propsData.label)
      if (name.toLowerCase().includes(input.toLowerCase())) {
        return true
      }
    },
    initProjectList() {
      getProjectList().then((res) => {
        if (res.success) {
          this.projectList = res.result
        }
      })
    },
    configSetting(index, selectedKey, record) {
      if (selectedKey) {
        record = this.dataSource.find(function(item) {
          return item.id === selectedKey
        })
      }
      this.$refs.configSettingModal.open(index, record)
    },
    openDoors(record) {
      this.loading = true
      getAction(this.url.openDoor, { sn: record.deviceSn }).then((res) => {
        if (res.success) {
          this.$message.success('开门指令发送成功！')
        } else {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    handleAdd() {
      this.$refs.addDeviceModal.open()
    },
    handleEdit(record) {
      this.$refs.addDeviceModal.edit(record)
      this.$refs.addDeviceModal.title = '编辑'

    },
    onChangeStartTime(date, dateString) {
      this.queryParam.opTime_begin = dateString
    },

    onChangeEndTime(date, dateString) {
      this.queryParam.opTime_end = dateString
    },


    searchQuery() {
      let startTime = this.queryParam.opTime_begin
      let endTime = this.queryParam.opTime_end
      console.log('----------' + this.queryParam.deviceCode)
      if (startTime != '' && endTime != '') {
        if (startTime > endTime) {
          this.$message.error('开始时间不能大于结束时间')
          return
        }
      }

      if (startTime == '' && endTime != '') {
        this.$message.error('请选择开始时间')
        return
      }

      if (startTime != '' && endTime == '') {
        this.$message.error('请选择结束时间')
        return
      }

      this.loadData(1)
    },

    getQueryParams() {
      var param = Object.assign({}, this.isorter, this.queryParam)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      if (this.queryParam.opTime_begin != '' && this.queryParam.opTime_end != '') {
        param.opTime_begin = this.queryParam.opTime_begin + ' 00:00:00'
        param.opTime_end = this.queryParam.opTime_end + ' 23:59:59'
      }
      return filterObj(param)
    },

    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams()//查询条件
      console.log('@@@@', params)
      this.loading = true
      getAction(this.url.list, params).then((res) => {
        if (res.success && res.result != null) {
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },

    batchDel: function() {

      if (!this.url.deleteBatch) {
        this.$message.error('请设置url.deleteBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        let ids = ''
        for (let a = 0; a < this.selectionRows.length; a++) {
          ids += this.selectionRows[a].id + ','
        }
        let that = this
        this.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: function() {
            deleteAction(that.url.deleteBatch, { ids: ids }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },
    handleDelete: function(id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      var that = this
      deleteAction(that.url.delete, { id: id }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    keyupEnter() {
      document.onkeydown = e => {
        let body = document.getElementsByTagName('body')[0]
        if (e.keyCode === 13) {
          this.loadData(1)
        }
      }
    },
    searchTypeList() {

      this.typeLoadData()
    },
    typeLoadData() {
      if (!this.url.typeList) {
        this.$message.error('请设置url.list属性!')
        return
      }
      getAction(this.url.typeList, null).then((res) => {
        if (res.success) {
          this.deviceTypeList = res.result.records

        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
      })
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>